﻿using System;
using System.Diagnostics;

using Kingdee.BOS;
using Kingdee.BOS.Log;
using Kingdee.BOS.Orm.DataEntity;
using Kingdee.BOS.ServiceHelper;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace Hamster.K3Cloud.WebAPI.ServerExtend
{
    public class Utils
    {
        /// <summary>
        /// 打印日志
        /// </summary>
        /// <param name="formId">单据ID</param>
        /// <param name="eventName">动作名称</param>
        /// <param name="args">参数</param>
        public void PrintLog(string formId, string eventName, params object[] args)
        {
            var parameters = string.Empty;
            try
            {
                parameters = JsonConvert.SerializeObject(args);
            }
            catch { }
            var log = string.Format("执行时间:{0},表单Id:{1},事件名称:{2},事件参数:{3}",
                DateTime.Now.ToString(),
                formId,
                eventName,
                parameters);
            Debug.Print(log);
            Logger.Error("===HamsterLog===", log, null);
        }

        /// <summary>
        /// 获取客户端传递的参数中的源单明细内码
        /// </summary>
        /// <param name="parameter"></param>
        /// <returns></returns>
        public static JArray getSrcEntryIds(Parameter parameter)
        {
            if (parameter.Model.Property(parameter.NextEntryKey) == null)
            {
                return new JArray();
            }

            JArray entryData = parameter.Model[parameter.NextEntryKey] as JArray;
            JArray srcEntryIds = new JArray();
            foreach (JObject item in entryData)
            {
                foreach (JProperty field in item.Properties())
                {
                    if (field.Name == Defineds.FSrcEntryID)
                    {
                        srcEntryIds.Add(field.Value);
                    }
                }
            }

            return srcEntryIds;
        }

        /// <summary>
        /// 获取源单内码和下推单据内码对应关系
        /// TODO 需要整理表名和FormID的对应关系
        /// </summary>
        /// <param name="context">上下文</param>
        /// <param name="tableName">下推表表名</param>
        /// <param name="fsTableName">源单表名</param>
        /// <param name="entryIds">源单明细内码</param>
        /// <returns></returns>
        public static DynamicObjectCollection getEntryLinkID(Context context, string tableName, string fsTableName, JArray entryIds)
        {
            const string entryTableSuffix = "ENTRY";
            const string entryTableSuffixSub = "DATA";
            const string entryLinkTableSuffix = "ENTRY_LK";
            const string entryLinkTableSuffixSub = "DATA_LK";

            tableName = "T_" + tableName;
            if (tableName == "T_STK_TransferDirect") // 直接调拨单FormID和表名规则不一致（表名不一致）
            {
                tableName = "T_STK_STKTRANSFERIN";
            }
            else if (tableName == "T_STK_TRANSFEROUT")  // 分步式调出单表名与规则不一致。
            {
                tableName = "T_STK_STKTRANSFEROUT";
            }
            else if (tableName == "T_STK_TRANSFERIN")     // 分步式调入单
            {
                tableName = "T_STK_STKTRANSFERIN";
            }

            var tbeName = tableName + entryTableSuffix;
            var tbelName = tableName + entryLinkTableSuffix;
            if (tableName == "T_PRD_PICKMTRL" || tableName == "T_PRD_FEEDMTRL") // 生产领料单和生产补料单和其他表不一致(后缀不一致)
            {
                tbeName = tableName + entryTableSuffixSub;
                tbelName = tableName + entryLinkTableSuffixSub;
            }

            // Windows环境下数据库会忽略大小写
            fsTableName = "T_" + fsTableName;
            string sql = string.Format(@" SELECT th.FID,tlk.FSID,tlk.FENTRYID 
                FROM {0} tlk 
                INNER JOIN {1} te ON te.FENTRYID=tlk.FENTRYID 
                INNER JOIN {2} th ON th.FID=te.FID
                WHERE tlk.FSTABLENAME='{3}' 
                AND FSID IN ({4})", tbelName, tbeName, tableName, fsTableName, string.Join(",", entryIds));
            return DBServiceHelper.ExecuteDynamicObject(context, sql);
        }
    }
}
